package com.medicinezp.framework.web.service;

import com.medicinezp.baseconfig.domain.BaseCompany;
import com.medicinezp.baseconfig.domain.BaseCompanyAccountReal;
import com.medicinezp.baseconfig.service.IBaseCompanyAccountRealService;
import com.medicinezp.baseconfig.service.IBaseCompanyService;
import com.medicinezp.common.utils.DateUtils;
import com.medicinezp.common.utils.bean.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.medicinezp.common.constant.CacheConstants;
import com.medicinezp.common.constant.Constants;
import com.medicinezp.common.constant.UserConstants;
import com.medicinezp.common.core.domain.entity.SysUser;
import com.medicinezp.common.core.domain.model.RegisterBody;
import com.medicinezp.common.core.redis.RedisCache;
import com.medicinezp.common.exception.user.CaptchaException;
import com.medicinezp.common.exception.user.CaptchaExpireException;
import com.medicinezp.common.utils.MessageUtils;
import com.medicinezp.common.utils.SecurityUtils;
import com.medicinezp.common.utils.StringUtils;
import com.medicinezp.framework.manager.AsyncManager;
import com.medicinezp.framework.manager.factory.AsyncFactory;
import com.medicinezp.system.service.ISysConfigService;
import com.medicinezp.system.service.ISysUserService;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 注册校验方法
 *
 * @author medicinezp
 */
@Component
public class SysRegisterService
{
    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private IBaseCompanyService baseCompanyService;

    @Autowired
    private IBaseCompanyAccountRealService baseCompanyAccountRealService;

    /**
     * 注册
     */
    @Transactional
    public String register(RegisterBody registerBody)
    {
        String password = configService.selectConfigByKey("sys.user.initPassword");
        String msg = "", username = registerBody.getContactName();
        SysUser sysUser = new SysUser();
        sysUser.setUserName(registerBody.getContactPhone());
        sysUser.setNickName(username);
        sysUser.setPhonenumber(registerBody.getContactPhone());
        if (StringUtils.isEmpty(username))
        {
            msg = "用户名不能为空";
        }
        else if (StringUtils.isEmpty(registerBody.getCompanyName()))
        {
            msg = "公司名称不能为空";
        }
        else if (StringUtils.isEmpty(registerBody.getShortName()))
        {
            msg = "公司简称不能为空";
        }
        else if (StringUtils.isEmpty(registerBody.getBusinessLicense()))
        {
            msg = "营业执照编码不能为空";
        }
        else if (StringUtils.isEmpty(registerBody.getContactPhone()))
        {
            msg = "联系电话不能为空";
        }
        else if (username.length() < UserConstants.USERNAME_MIN_LENGTH
                || username.length() > UserConstants.USERNAME_MAX_LENGTH)
        {
            msg = "账户长度必须在2到20个字符之间";
        }
        else if (UserConstants.NOT_UNIQUE.equals(userService.checkUserNameUnique(sysUser)))
        {
            msg = "保存用户'" + username + "'失败，注册账号已存在";
        }
        else if (UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(sysUser)))
        {
            msg = "新增入驻企业失败，联系电话已存在";
        }
        else
        {
            BaseCompany param=new BaseCompany();
            param.setCompanyName(registerBody.getCompanyName());
            param.setUniformSocialCreditCode(registerBody.getUniformSocialCreditCode());
            List<BaseCompany> compnayList= baseCompanyService.selectBaseCompanyExtistsList(param);
            if(compnayList.size()==0) {
                sysUser.setNickName(username);
                sysUser.setStatus("1");
                sysUser.setPhonenumber(registerBody.getContactPhone());
                sysUser.setPassword(SecurityUtils.encryptPassword(password));
                boolean regFlag = userService.registerUser(sysUser);
                if (!regFlag) {
                    msg = "注册失败,请联系系统管理人员";
                } else {
                    BaseCompany company = new BaseCompany();
                    BeanUtils.copyBeanProp(company, registerBody);
                    company.setAuditStatus("01");
                    company.setAvailableFlag("Y");
                    baseCompanyService.insertBaseCompany(company);
                    BaseCompanyAccountReal baseCompanyAccountReal = new BaseCompanyAccountReal();
                    baseCompanyAccountReal.setCompanyId(company.getId());
                    baseCompanyAccountReal.setUserId(sysUser.getUserId());
                    baseCompanyAccountReal.setUserPhone(sysUser.getPhonenumber());
                    baseCompanyAccountReal.setUserName(sysUser.getUserName());
                    baseCompanyAccountReal.setIsMain("Y");
                    baseCompanyAccountReal.setStatus("Y");
                    baseCompanyAccountReal.setCreateTime(DateUtils.getNowDate());
                    baseCompanyAccountReal.setCreateBy(sysUser.getUserName());
                    baseCompanyAccountRealService.insertBaseCompanyAccountReal(baseCompanyAccountReal);
                    AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.REGISTER, MessageUtils.message("user.register.success")));
                }
            }else{
                BaseCompany company = new BaseCompany();
                BeanUtils.copyBeanProp(company, registerBody);
                company.setAuditStatus("01");
                company.setAvailableFlag("Y");
                company.setId(compnayList.get(0).getId());
                baseCompanyService.updateBaseCompany(company);
                BaseCompanyAccountReal rela=new BaseCompanyAccountReal();
                rela.setCompanyId(company.getId());
                userService.updateUserAuthDisable(company.getId());
            }
        }
        return msg;
    }

    /**
     * 校验验证码
     *
     * @param username 用户名
     * @param code 验证码
     * @param uuid 唯一标识
     * @return 结果
     */
    public void validateCaptcha(String username, String code, String uuid)
    {
        String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + StringUtils.nvl(uuid, "");
        String captcha = redisCache.getCacheObject(verifyKey);
        redisCache.deleteObject(verifyKey);
        if (captcha == null)
        {
            throw new CaptchaExpireException();
        }
        if (!code.equalsIgnoreCase(captcha))
        {
            throw new CaptchaException();
        }
    }
}
